﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Framework.Library;
using Framework.Library.Components.Portal;
using Framework.Library.Components.Roles;
using Framework.Library.Components.Security;
using Framework.Library.Components.Users;
using Framework.Library.Utilities;
using Framework.Library.Components.Commands;
namespace Portal.Administrator.Users
{
    public partial class CreateUser : AuthenticatedControl
    {        
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);
            if (CurrentUser.IsSuperAdmin)
            {
                pnlSuperadmin.Visible = true;
            }

            if (!Page.IsPostBack)
            {
                PortalController.LoadPortalsForUserID(lstPortal.Items, CurrentUser.UserID);
                lstPortal.SelectedIndex = -1;
                TimeZones.DataSource = StaticData.TimeZones();
                TimeZones.DataBind();
                Suspended.DataSource = StaticData.Suspended();
                Suspended.DataBind();
                lblCommandName.Text = AppEnv.CommandName();
                if (!String.IsNullOrEmpty(Request.QueryString["uid"]))
                {
                    btnUpdate.CommandName = "update";
                    DataBinds();
                }
            }
        }
        private void DataBinds()
        {
            int userId = ConvertUtility.ToInt32(Request.QueryString["uid"]);
            UserInfo user = UserController.GetUser(userId);
            if (user != null)
            {
                txtUsername.Text = user.Username;
                txtName.Text = user.Name;
                hddCurPassword.Value = user.Password;
                txtDisplayName.Text = user.DisplayName;
                txtEmail.Text = user.Email;
                txtTel.Text = user.Tel;
                txtMobile.Text = user.Mobile;
                txtAddress.Text = user.Address;
                chkIsSuperAdmin.Checked = user.IsSuperAdmin;
                TimeZones.SelectedValue = Convert.ToString(user.TimeZone);
                chkIsApproval.Checked = user.IsApproved;                
                PMNotification.Checked = user.PMNotification;
                DataTable dtUserPortals = PortalController.GetPortals(user.UserID);
                foreach (DataRow row in dtUserPortals.Rows)
                {
                    if (lstPortal.Items.FindByValue(row["PortalID"].ToString()) != null)
                    {
                        lstPortal.Items.FindByValue(row["PortalID"].ToString()).Selected = true;
                    }
                }
            }
        }
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (txtPassword.Text.Trim() != txtPasswordConfirm.Text.Trim()) return;                
                    UserInfo user = new UserInfo();
                    user.Username = txtUsername.Text.Trim();                    
                    user.Name = txtName.Text;
                    user.DisplayName = txtDisplayName.Text.Trim();
                    user.Email = txtEmail.Text;
                    user.Tel = txtTel.Text.Trim();
                    user.Mobile = txtMobile.Text.Trim();
                    user.Address = txtAddress.Text.Trim();
                    user.IsSuperAdmin = chkIsSuperAdmin.Checked;
                    user.Joined = DateTime.Now;
                    user.LastVisit = DateTime.Now;
                    user.IP = HttpContext.Current.Request.UserHostAddress;
                    user.TimeZone = Convert.ToInt32(TimeZones.SelectedValue);
                    user.IsApproved = chkIsApproval.Checked;
                    TimeSpan tmpSuspend = new TimeSpan(Convert.ToInt32(Suspended.SelectedValue), 0, 0, 0);
                    DateTime dtmSuspend = DateTime.Now + tmpSuspend;
                    user.Suspended = dtmSuspend;
                    user.PMNotification = PMNotification.Checked;
                    int userId = 0;
                    try
                    {                        
                        if (btnUpdate.CommandName != "update")
                        {
                            user.Password = SecurityMethod.MD5Encrypt(txtPassword.Text.Trim());
                            userId = UserController.AddUser(user);
                            foreach (ListItem item in lstPortal.Items)
                            {
                                if (item.Selected)
                                {
                                    RoleController.AddUserToRole(userId, AppEnv.DEFAULT_ROLE, ConvertUtility.ToInt32(item.Value));
                                }
                            }
                        }
                        else
                        {
                            if (txtPassword.Text == "" || txtPassword.Text == "password")
                                user.Password = hddCurPassword.Value;                            
                            else
                                user.Password = SecurityMethod.MD5Encrypt(txtPassword.Text.Trim());
                            user.UserID = Convert.ToInt32(Request.QueryString["uid"]);
                            userId = user.UserID;
                            UserController.EditUser(user);
                            DataTable dtUserRoles = RoleController.GetRoles(userId);
                            int RoleID = 0;
                            foreach (DataRow row in dtUserRoles.Rows)
                            {
                                RoleID = Convert.ToInt32(row["RoleID"]);
                            }
                            foreach (ListItem item in lstPortal.Items)
                            {
                                if (item.Selected)
                                {
                                    RoleController.UpdateUserToRole(user.UserID, RoleID, Convert.ToInt32(item.Value));
                                }
                                else
                                {
                                    RoleController.RemoveUserFromRole(user.UserID, RoleID, Convert.ToInt32(item.Value));
                                }
                            }
                        }                        
                    }
                    catch (Exception ex)
                    {
                        lblUpdateStatus.Text = ex.Message;
                    }                    
                    lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;                
            }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.UserManage)));
        }
    }
}